<template>
  <div class="journal-part-1">
    <div class="part-title">Part I - {{ $t("btnText.task.part_1") }}</div>
    <div class="part-form" v-if="formData">
      <a-form
        :model="formData"
        class="ant-form"
        ref="formRef"
        label-align="left"
      >
        <div class="row">
          <div class="col">
            <a-form-item :label="$t('form.task.part_1_form.item_1.label')">
              <a-date-picker
                @change="onFormDateChange"
                v-model:value="formData.book_open_date"
              >
                <template #suffixIcon>
                  <IconCalendar class="icon-calendar"></IconCalendar>
                </template>
              </a-date-picker>
            </a-form-item>
          </div>
          <div class="col">
            <a-form-item :label="$t('form.task.part_1_form.item_2.label')">
              <a-input
                @blur="onFormDataChange"
                v-model:value="formData.name"
              ></a-input>
            </a-form-item>
          </div>
        </div>
        <div class="row">
          <div class="col">
            <a-form-item :label="$t('form.task.part_1_form.item_3.label')">
              <a-date-picker
                @change="onFormDateChange"
                v-model:value="formData.date_of_birth"
              >
                <template #suffixIcon>
                  <IconCalendar class="icon-calendar"></IconCalendar>
                </template>
              </a-date-picker>
            </a-form-item>
          </div>
          <div class="col">
            <a-form-item :label="$t('form.task.part_1_form.item_4.label')">
              <a-input
                @blur="onFormDataChange"
                v-model:value="formData.place_of_birth"
              ></a-input
            ></a-form-item>
          </div>
        </div>
        <div class="row">
          <div class="col">
            <a-form-item :label="$t('form.task.part_1_form.item_5.label')">
              <a-input
                @blur="onFormDataChange"
                v-model:value="formData.country"
              ></a-input>
            </a-form-item>
          </div>
          <div class="col">
            <a-form-item :label="$t('form.task.part_1_form.item_6.label')">
              <a-input
                @blur="onFormDataChange"
                v-model:value="formData.passport"
              ></a-input>
            </a-form-item>
          </div>
        </div>
        <div class="row">
          <div class="col">
            <a-form-item
              :label="$t('form.task.part_1_form.item_7.label')"
              name="email"
              :rules="[
                {
                  validator: validateEmail,
                  trigger: 'blur',
                },
              ]"
            >
              <a-input
                @blur="onFormDataChange('email')"
                v-model:value="formData.email"
              ></a-input>
            </a-form-item>
          </div>
          <div class="col">
            <a-form-item :label="$t('form.task.part_1_form.item_8.label')">
              <a-input
                @blur="onFormDataChange"
                v-model:value="formData.years_of_experience"
              ></a-input>
            </a-form-item>
          </div>
        </div>
        <div class="row">
          <div class="col">
            <a-form-item :label="$t('form.task.part_1_form.item_9.label')">
              <a-textarea
                :maxlength="1000"
                @blur="onFormDataChange"
                v-model:value.trim="formData.eduction_level"
                :autoSize="eduAreaRows"
              ></a-textarea>
              <div class="tips">
                {{ $t("form.task.part_1_form.item_9.tip") }}
              </div>
            </a-form-item>
          </div>
          <div class="tips">{{ $t("form.task.part_1_form.item_9.tip") }}</div>
          <div class="col auth">
            <a-form-item :label="$t('form.task.part_1_form.item_10.label')">
              <a-textarea
                :maxlength="1000"
                @blur="onFormDataChange"
                v-model:value.trim="formData.qualifications"
                :autoSize="authAreaRows"
              ></a-textarea>
              <div class="tips">
                {{ $t("form.task.part_1_form.item_10.tip") }}
              </div>
            </a-form-item>
          </div>
          <div class="tips">{{ $t("form.task.part_1_form.item_10.tip") }}</div>
        </div>
      </a-form>
    </div>
    <div class="footer-btn">
      <a-button @click="goto('/profile/journal')">{{
        $t("btnText.prev_step")
      }}</a-button>
      <a-button type="primary" @click="goto('/member/journal', { step: 2 })">{{
        $t("btnText.next_step")
      }}</a-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, getCurrentInstance } from "vue";
import { postPartOneUpdate, postPartOneView } from "../../../../api/part";
import type { PartOne } from "../../../../types/part";
import { RegDateYYYYMMDD, RegEmail } from "../../../../data/reg";
import dayjs from "dayjs";
import { useMemberStore } from "../../../../store";
import { message } from "ant-design-vue";
const memberStore = useMemberStore();
const $t = getCurrentInstance()?.appContext.config.globalProperties.$t;

const formData = ref<PartOne>({
  book_open_date: "",
  name: "",
  date_of_birth: "",
  place_of_birth: "",
  country: "",
  passport: "",
  email: "",
  years_of_experience: "",
  eduction_level: "",
  qualifications: "",
  member_id: memberStore.profile?.id,
});
const getPartOneData = async () => {
  let res = await postPartOneView();
  if (res.code === 200) {
    res.data ? (formData.value = res.data) : null;
    formData.value.date_of_birth &&
    RegDateYYYYMMDD.test(formData.value.date_of_birth)
      ? (formData.value.date_of_birth = formatDate(
          formData.value.date_of_birth
        ))
      : (formData.value.date_of_birth = "");
    formData.value.book_open_date &&
    RegDateYYYYMMDD.test(formData.value.book_open_date)
      ? (formData.value.book_open_date = formatDate(
          formData.value.book_open_date
        ))
      : (formData.value.book_open_date = "");
    setCacheData();
  }
};

// ====================表单事件================================================================
let cacheFormData: PartOne = {
  book_open_date: "",
  name: "",
  date_of_birth: "",
  place_of_birth: "",
  country: "",
  passport: "",
  email: "",
  years_of_experience: "",
  eduction_level: "",
  qualifications: "",
};
const formRef = ref();
const onFormDataChange = (type?: string) => {
  if (type == "email") {
    if (RegEmail.test(formData.value.email)) {
      updateInfo();
    } else {
      message.warning($t("reg_rules.email"));
    }
    return;
  }
  if (checkFormValueChanged()) {
    updateInfo();
  }
};

const onFormDateChange = () => {
  updateInfo();
};

const setCacheData = () => {
  cacheFormData = JSON.parse(JSON.stringify(formData.value));
};
const checkFormValueChanged = () => {
  let data = formData.value;
  let flag = false;
  // if(data.book_open_date != cacheFormData?.book_open_date) flag = true
  if (data.name != cacheFormData?.name) flag = true;
  // if(data.date_of_birth != cacheFormData?.date_of_birth) flag = true
  if (data.place_of_birth != cacheFormData?.place_of_birth) flag = true;
  if (data.country != cacheFormData?.country) flag = true;
  if (data.passport != cacheFormData?.passport) flag = true;
  if (data.email != cacheFormData?.email) flag = true;
  if (data.years_of_experience != cacheFormData?.years_of_experience)
    flag = true;
  if (data.eduction_level != cacheFormData?.eduction_level) flag = true;
  if (data.qualifications != cacheFormData?.qualifications) flag = true;
  return flag;
};

const updateInfo = async () => {
  let obj = {
    book_open_date: "",
    date_of_birth: "",
  };
  if (formData.value.book_open_date) {
    obj.book_open_date = dayjs(formData.value.book_open_date).format(
      "YYYY-MM-DD"
    );
  }
  if (formData.value.date_of_birth) {
    obj.date_of_birth = dayjs(formData.value.date_of_birth).format(
      "YYYY-MM-DD"
    );
  }
  let params = JSON.parse(JSON.stringify(formData.value));
  Object.assign(params, obj);
  let res = await postPartOneUpdate(params);
  if (res.code === 200) {
    setCacheData();
  }
};

const validateEmail = async (rule: any, value: string) => {
  if (!RegEmail.test(value)) {
    return Promise.reject($t("reg_rules.email"));
  }
  return Promise.resolve();
};

const eduAreaRows = ref({ minRows: 3, maxRows: 3 });
const authAreaRows = ref({ minRows: 3, maxRows: 3 });

const resetRows = () => {
  if (isMobile()) {
    eduAreaRows.value.maxRows = 2;
    eduAreaRows.value.minRows = 2;
    authAreaRows.value.maxRows = 1;
    authAreaRows.value.minRows = 1;
  } else {
    eduAreaRows.value.maxRows = 3;
    eduAreaRows.value.minRows = 3;
    authAreaRows.value.maxRows = 3;
    authAreaRows.value.minRows = 3;
  }
};
onMounted(async () => {
  await getPartOneData();
  resetRows();
  window.addEventListener("resize", resetRows);
});
</script>
<style scoped lang="less">
@import url("./common.less");
@media screen and (max-width: 768px) {
  .journal-part-1 {
    padding: 123px;
    border-radius: 82px;
    border: 1px solid #ccd6de;
  }
}
</style>
